package org.inspursc.s0517.health.evaluation.controller;

import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.inspursc.s0517.health.common.util.LogUtil;
import org.inspursc.s0517.health.common.util.ResponseUtil;
import org.inspursc.s0517.health.common.vo.ResponseVO;
import org.inspursc.s0517.health.evaluation.dao.OrganizationDao;
import org.inspursc.s0517.health.evaluation.dto.AssessmentNumDTO;
import org.inspursc.s0517.health.evaluation.dto.InsSurveyAnswerDTO;
import org.inspursc.s0517.health.evaluation.dto.OrgAndAssessListDTO;
import org.inspursc.s0517.health.evaluation.entity.Organization;
import org.inspursc.s0517.health.evaluation.service.InsSurveyAnswerService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping(value = "/org")
public class OrganizationController {
    @Autowired
    OrganizationDao organizationDao;

    @Autowired
    InsSurveyAnswerService insSurveyAnswerService;

    @Autowired
    LogUtil logUtil;

    @ApiOperation("增加或修改机构信息")
    @PostMapping(value = "/save")
    public ResponseEntity<ResponseVO> save(@ApiParam("机构信息") @RequestBody @Valid Organization organization, BindingResult bindingResult, HttpServletRequest request) {
        if (bindingResult.hasErrors()) {
            return ResponseUtil.error400(bindingResult.getFieldError().getDefaultMessage(), null);
        }
        try {
            // 资质验证
            if(!organization.getPermit().equals("false") &&
                    !organization.getFirePermit().equals("false") &&
                    !organization.getHouseProperty().equals("false") &&
                    !organization.getFoodPermit().equals("false") &&
                    !organization.getMedicalLicense().equals("false") &&
                    !organization.getSpecialEquipmentPermit().equals("false")){
                organization.setIsPass(true);
            }
            Organization  newOrganization = organizationDao.save(organization);
            return ResponseUtil.success("保存/修改成功", newOrganization);
        } catch (Exception e) {
            return ResponseUtil.error(e.getMessage(), "保存/修改失败");
        }
    }

    @ApiOperation(value = "根据id删除记录")
    @DeleteMapping("/deleteById/{id}")
    public ResponseEntity<ResponseVO> delete(@ApiParam(value = "ID", required = true) @PathVariable Integer id) {
        try {
            organizationDao.deleteById(id);
            return ResponseUtil.success("删除成功", true);
        } catch (Exception e) {
            return ResponseUtil.error(e.getMessage(), null);
        }
    }

    @ApiOperation(value = "根据ID获取信息")
    @GetMapping(value = "/getById")
    public ResponseEntity<ResponseVO> getOrganization(@ApiParam("ID") @RequestParam(value = "id") Integer id) {
        try {
            Optional<Organization> optionalOrganization = organizationDao.findById(id);
            Organization organization = optionalOrganization.get();
            if (null != organization) {
                return ResponseUtil.success("获取用户成功！", organization);
            } else {
                return ResponseUtil.error404("不存在!", null);
            }
        } catch (Exception e) {
            return ResponseUtil.error("系统异常：" + e.getMessage(), null);
        }
    }

    @ApiOperation(value = "获取信息")
    @GetMapping(value = "/listAll")
    public ResponseEntity<ResponseVO> listAll(HttpServletRequest request) {
        try {
            List<Organization> organizations = organizationDao.findAll();
            if (null != organizations) {
                return ResponseUtil.success("ok", organizations);
            } else {
                return ResponseUtil.error404("沒有信息，请添加！", null);
            }
        } catch (Exception e) {
            return ResponseUtil.error(e.getMessage(), null);
        }
    }

    @ApiOperation(value = "分页获取信息")
    @GetMapping(value = "/listByPage")
    public ResponseEntity<ResponseVO> listByPage(HttpServletRequest request, Integer pageSize, Integer pageNum) {
        try {
            Sort sort = new Sort(Sort.Direction.DESC,"id");
            Pageable pageable = PageRequest.of(pageNum - 1, pageSize, sort);
            Page<Organization> organizations = organizationDao.findAll(pageable);
            Page<OrgAndAssessListDTO> orgAndAssessListDTOs = null;
            if(organizations != null) {
                orgAndAssessListDTOs = organizations.map(organization -> {
                    OrgAndAssessListDTO orgAndAssessListDTO = new OrgAndAssessListDTO();
                    BeanUtils.copyProperties(organization, orgAndAssessListDTO);
                    List<InsSurveyAnswerDTO> insSurveyAnswerDTOs = insSurveyAnswerService.findAllByOrganizationId(organization.getId());
                    List<AssessmentNumDTO> assessmentNumDTOs = new ArrayList<>();
                    if (insSurveyAnswerDTOs != null) {
                        for (InsSurveyAnswerDTO assessment : insSurveyAnswerDTOs) {
                            AssessmentNumDTO numDTO = new AssessmentNumDTO();
                            numDTO.setSuName(assessment.getSurveyName());
                            numDTO.setSuId(assessment.getSurveyId());
                            numDTO.setSuAnswerId(assessment.getId());
                            numDTO.setDateTime(new SimpleDateFormat("yy-MM-dd").format(assessment.getDateTime()));
                            assessmentNumDTOs.add(numDTO);
                        }
                    }
                    orgAndAssessListDTO.setAssessment(assessmentNumDTOs);
                    return orgAndAssessListDTO;
                });
            }
            return ResponseUtil.success("ok", orgAndAssessListDTOs);
        } catch (Exception e) {
            return ResponseUtil.error(e.getMessage(), null);
        }
    }
}
